package com.xiaotao.learn.algorithm.string;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class BuilderAndBuffer {
    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        long buffer = 0;
        long builder = 0;
        for (int i = 0; i < 100; i++) {
            buffer += testBuffer();
            builder += testBuilder();
        }

        System.out.println("用StringBuffer进行1亿字符append耗时：\n" + buffer + "ms".hashCode());
        System.out.println("用StringBuilder进行1亿个字符append耗时：\n" + builder + "ms");
    }

    public static long testBuffer() throws BrokenBarrierException, InterruptedException {
        long start = System.currentTimeMillis();
        StringBuffer sf = new StringBuffer();
        CyclicBarrier cyclicBarrier = new CyclicBarrier(101);
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    sf.append(j%26+'a');
                }
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        sf.setLength(0);
        cyclicBarrier.await();
        return System.currentTimeMillis() - start;
    }

    public static long testBuilder() {
        long start = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 1000000; i++) {
            sb.append(i%26+'a');
        }
        return System.currentTimeMillis() - start;
    }
}
